#include "Translator.h"

#include <QFile>
#include <QDebug>
#include <QApplication>
#include <QStringList>

Translator* getTranslator(const QString& locale)
{
    static Translator tr;
    if(locale != "")
        tr.changeLocale(locale);
    return &tr;
}

bool Translator::changeLocale(const QString& locale)
{
    QString fileName = QApplication::applicationDirPath() + "/Translates/" + locale + ".trad";
    QFile file(fileName);

    if(!file.open(QIODevice::ReadOnly | QIODevice::Text))
    {
        qDebug() << "No states traductions avaible for \"" + locale + "\" : file \"" + fileName + "\" is missing.";
        return true;
    }

    while (!file.atEnd())
    {
        QString line = file.readLine();
        if(line.isEmpty())
            continue;
        line = line.replace("\n", "");
        int i = line.indexOf(';');
        m_table[line.left(i)] = line.mid(i+1);
    }

    qDebug() << locale << " state traduction file succefully loaded";
    return false;
}

QString Translator::translate(const QString& s) const
{
    return m_table.value(s, s);
}

QString Translator::unTranslate(const QString& s) const
{
    return m_table.key(s, s);
}

QStringList Translator::unTranslate(const QStringList& s) const
{
    QStringList l;
    for(int i = 0; i < s.size(); ++i)
    {
        l.append(m_table.key(s[i], s[i]));
    }
    return l;
}

QStringList Translator::translate(const QStringList& s) const
{
    QStringList l;
    for(int i = 0; i < s.size(); ++i)
    {
        l.append(m_table.value(s[i], s[i]));
    }
    return l;
}
